<?php

/**
 * ECSHOP 订单管理
 * ============================================================================
 * 版权所有 2005-2010 成都如花贸易有限公司，并保留所有权利。
 * 网站地址: http://www.airuhua.com ；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: yehuaixiao $
 * $Id: order.php 17157 2010-05-13 06:02:31Z yehuaixiao $
 */

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
require_once(ROOT_PATH . 'includes/lib_order.php');
require_once(ROOT_PATH . 'includes/lib_goods.php');
include_once ROOT_PATH.'includes/modules/taobao/TopSdk.php';
include_once ROOT_PATH.'includes/modules/taobao/top/RequestCheckUtil.php';
include_once ROOT_PATH.'includes/modules/taobao/top/TopClient.php';

set_time_limit(0);

/*------------------------------------------------------ */
//-- 评价处理
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'order_rate_get')
{
	$tid = $_REQUEST['tid'];
	
	$c = new TopClient();
	include_once ROOT_PATH.'includes/modules/taobao/top/request/TraderatesGetRequest.php';
	$req = new TraderatesGetRequest();
	$req->setFields('tid,oid,role,nick,result,created,rated_nick,item_title,item_price,content,reply,num_iid');
	$req->setRateType('get');
	$req->setRole('buyer');
	$req->setTid($tid);
	
	$sql =  'SELECT session FROM '.$GLOBALS['ecs']->table('taobao').' WHERE id=1';
	$session = $GLOBALS['db']->getOne($sql);
	
	$res = $c->execute($req,$session);
	
	if(!isset($res->code)){
		if (isset($res->trade_rates->trade_rate)) {
			foreach ($res->trade_rates->trade_rate as $rate){
				make_json_result('','0','',array('created'=>$rate->created,'content'=>$rate->content,'result'=>$rate->result));
			}
		}		
	}else{
		if(isset($res->sub_msg)){
			$msg = $res->sub_msg;
		}else {
			$msg = $res->msg;
		}
		make_json_result('','1',$msg,array('code'=>$res->code,'tid'=>$tid));
	}
}
/*------------------------------------------------------ */
//-- 评价处理
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'order_rate')
{
	$tid = $_REQUEST['tid'];
	$result = $_REQUEST['result'];
	$content = $_REQUEST['content'];
	
	$c = new TopClient();
	include_once ROOT_PATH.'includes/modules/taobao/top/request/TraderateListAddRequest.php';
	$req = new TraderateListAddRequest();
	$req->setTid($tid);
	$req->setResult($result);
	$req->setRole('seller');
	$req->setAnony(false);
	$req->setContent($content);
	
	$sql =  'SELECT session FROM '.$GLOBALS['ecs']->table('taobao').' WHERE id=1';
	$session = $GLOBALS['db']->getOne($sql);
	
	$res = $c->execute($req,$session);
	
	if(!isset($res->code)){
		$sql = "UPDATE ".$GLOBALS['ecs']->table('taobao_order')." SET `seller_rate` = 1 WHERE tid={$tid}";
		$GLOBALS['db']->query($sql);
		make_json_result('');
	}else{
		if(isset($res->sub_msg)){
			$msg = $res->sub_msg;
		}else {
			$msg = $res->msg;
		}
		make_json_result('','1',$msg,array('code'=>$res->code,'tid'=>$tid));
	}
}
/*------------------------------------------------------ */
//-- 备注处理
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'order_memo_add')
{
	$tid = $_REQUEST['tid'];
	$memo = $_REQUEST['memo'];
	$flag = $_REQUEST['flag'];
	
	$c = new TopClient();
	include_once ROOT_PATH.'includes/modules/taobao/top/request/TradeMemoAddRequest.php';
	$req = new TradeMemoAddRequest();
	$req->setTid($tid);
	$req->setMemo($memo);
	$req->setFlag($flag);
	
	$sql =  'SELECT session FROM '.$GLOBALS['ecs']->table('taobao').' WHERE id=1';
	$session = $GLOBALS['db']->getOne($sql);
	
	$res = $c->execute($req,$session);
	
	if(!isset($res->code)){
		$sql = "UPDATE ".$GLOBALS['ecs']->table('taobao_order')." SET `seller_memo` = '{$memo}',`seller_flag` = '{$flag}' WHERE tid={$tid}";
		$GLOBALS['db']->query($sql);
		make_json_result('');
	}else{
		if(isset($res->sub_msg)){
			$msg = $res->sub_msg;
		}else {
			$msg = $res->msg;
		}
		make_json_result('','1',$msg,array('code'=>$res->code,'tid'=>$tid));
	}
}
if ($_REQUEST['act'] == 'order_memo_update')
{
	$tid = $_REQUEST['tid'];
	$memo = $_REQUEST['memo'];
	$flag = $_REQUEST['flag'];

	$c = new TopClient();
	include_once ROOT_PATH.'includes/modules/taobao/top/request/TradeMemoUpdateRequest.php';
	$req = new TradeMemoUpdateRequest();
	$req->setTid($tid);
	$req->setMemo($memo);
	$req->setFlag($flag);

	$sql =  'SELECT session FROM '.$GLOBALS['ecs']->table('taobao').' WHERE id=1';
	$session = $GLOBALS['db']->getOne($sql);

	$res = $c->execute($req,$session);

	if(!isset($res->code)){
		$sql = "UPDATE ".$GLOBALS['ecs']->table('taobao_order')." SET `seller_memo` = '{$memo}',`seller_flag` = '{$flag}' WHERE tid={$tid}";
		$GLOBALS['db']->query($sql);
		make_json_result('');
	}else{
		if(isset($res->sub_msg)){
			$msg = $res->sub_msg;
		}else {
			$msg = $res->msg;
		}
		make_json_result('','1',$msg,array('code'=>$res->code));
	}
}

/*------------------------------------------------------ */
//-- 发货处理
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'order_delivery')
{
	$tids = $_REQUEST['tid'];
	
	$c = new TopClient();
	include_once ROOT_PATH.'includes/modules/taobao/top/request/LogisticsDummySendRequest.php';
	$req = new LogisticsDummySendRequest();
	
	$sql =  'SELECT session FROM '.$GLOBALS['ecs']->table('taobao').' WHERE id=1';
	$session = $GLOBALS['db']->getOne($sql);
	
	$successCount = 0;
	
	$tidsarr = explode(',', $tids);
	foreach ($tidsarr as $value) {
		$req->setTid($value);
		$res = $c->execute($req,$session);
		
		if (!isset($res->code) && $res->shipping->is_success) {
			$sql = "UPDATE ".$GLOBALS['ecs']->table('taobao_order')." SET `status` = 'WAIT_BUYER_CONFIRM_GOODS' WHERE tid={$value}";
			$GLOBALS['db']->query($sql);
			
			$sql = "UPDATE ".$GLOBALS['ecs']->table('taobao_order_order')." SET `status` = 'WAIT_BUYER_CONFIRM_GOODS' WHERE tid={$value}";
			$GLOBALS['db']->query($sql);
			
			$successCount++;
		}
	}
	
	if ($successCount > 0) {
		make_json_result('.');
	}else{
		if (isset($res->code)) {
			if(isset($res->sub_msg)){
				$msg = $res->sub_msg;
			}else {
				$msg = $res->msg;
			}
		}
		make_json_result('.','1',$msg,array('code'=>$res->code));
	}
}

/*------------------------------------------------------ */
//-- 订单详情
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'order_info')
{
	$tid = $_REQUEST['tid'];
	
	$sql = "SELECT o.tid,o.seller_memo,o.seller_flag, o.payment, oo.`status`, o.alipay_no, oo.oid, oo.title, o.post_fee, o.receiver_name, o.receiver_status, o.receiver_city, o.receiver_state, o.receiver_district, o.receiver_address, o.receiver_zip, o.receiver_mobile, o.receiver_phone, oo.sku_properties_name, o.alipay_id, o.buyer_nick, o.buyer_area, oo.num, oo.total_fee, oo.price, o.pay_time, o.created, oo.num_iid, o.pic_path, o.buyer_message FROM ".$GLOBALS['ecs']->table('taobao_order')." AS o INNER JOIN ".$GLOBALS['ecs']->table('taobao_order_order')." AS oo ON o.tid = oo.tid WHERE o.tid = $tid";
	
	$rows = new ArrayObject();
	$rows = $GLOBALS['db']->getAll($sql);	
	
	if(!empty($rows)){
		$row = $rows[0];
		foreach($row as $k=>$v){
			$smarty->assign($k,$v);
		}
		
		make_json_result($smarty->fetch('taobao_order_info.html'), '', array());
	}
}

/*------------------------------------------------------ */
//-- 导入订单
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'order_import')
{
	$page_size = 40;
	
	$sql = 'SELECT last_import_time FROM '.$GLOBALS['ecs']->table('taobao_import').' WHERE id=1';
	$row = $GLOBALS['db']->getOne($sql);	
	
	$lastTime = $row;
	
	if ($lastTime == null) {
		$lastTime = "";
	}
	
	$sql =  'SELECT session FROM '.$GLOBALS['ecs']->table('taobao').' WHERE id=1';
	$row = $GLOBALS['db']->getOne($sql);	
	
	$session = $row;
	
	if ($lastTime != "") {
		order_import_increment($lastTime, $session);
	}
	
	$fields = 'seller_nick, buyer_nick, title, type, created, tid, seller_rate, buyer_rate, status, payment, discount_fee, adjust_fee, post_fee, total_fee, pay_time, end_time, modified, consign_time, buyer_obtain_point_fee, point_fee, real_point_fee, received_payment, pic_path, num_iid, num, price, cod_fee, cod_status, shipping_type, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address, receiver_zip, receiver_mobile, receiver_phone,seller_flag,alipay_id,alipay_no,is_lgtype,is_force_wlb,is_brand_sale,buyer_area,has_buyer_message, credit_card_fee,orders';
	
	
	include_once ROOT_PATH.'includes/modules/taobao/top/request/TradesSoldGetRequest.php';
	include_once ROOT_PATH.'includes/modules/taobao/top/request/TradesSoldIncrementGetRequest.php';
	include_once ROOT_PATH.'includes/modules/taobao/top/request/TradeFullinfoGetRequest.php';
	$c = new TopClient;
	
	$req = new TradesSoldGetRequest();

	$page = 1;
	
	$req->setFields($fields);
	$req->setStartCreated(date('Y-m-d H:i:s',strtotime('-1 month',local_gettime())));
	$req->setPageSize($page_size);
	$req->setPageNo($page);
	$res = $c->execute($req, $session);
	
	if(!empty($res->code))
	{
		if($res->code == "27"){
			$url = 'http://container.api.taobao.com/container?appkey='.$c->appkey.'&encode=utf-8';
			make_json_result('','1','淘宝帐户已过期，请重新登录。',array('url'=>$url,'code'=>$res->code));
		}else{
			if(isset($res->sub_msg)){
				$msg = $res->sub_msg;
			}else {
				$msg = $res->msg;
			}
			make_json_result('','1',$msg,array('code'=>$res->code));
		}
	}
	
	$total = $res->total_results;
	
	$currNum = 0;
	while($total > ($page-1) * $page_size)
	{
		
		
		if($page>1){
			$req->setPageNo($page);
			$res = $c->execute($req, $session);
		}
		
		$page++;
		
		
		if (!empty($res->trades->trade))
		{
			foreach ($res->trades->trade as $trade )
			{
// 				$currNum++;
// 				make_json_info($currNum, $total);
				
				$tid =	sprintf('%.0f',$trade->tid);
				$sql = "SELECT tid FROM " . $GLOBALS['ecs']->table('taobao_order') . " WHERE tid = '$tid'";
				
				$agency_id = $GLOBALS['db']->getOne($sql);
				
				$trade->tid = $tid;
				if (empty($agency_id))
				{
					$GLOBALS['db']->autoExecuteJson($GLOBALS['ecs']->table('taobao_order'), $trade, 'INSERT', '', 'SILENT');
					if ($error_no > 0 && $error_no != 1062)
					{
						die($GLOBALS['db']->errorMsg());
					}				
				}
				else
				{
					$GLOBALS['db']->autoExecuteJson($GLOBALS['ecs']->table('taobao_order'), $trade, 'UPDATE', '`tid`='.$tid, 'SILENT');
					if ($error_no > 0 && $error_no != 1062)
					{
						die($GLOBALS['db']->errorMsg());
					}
				}
				
				foreach($trade->orders->order as $order)
				{
					$oid =	sprintf('%.0f',$order->oid);
					$sql = "SELECT tid FROM " . $GLOBALS['ecs']->table('taobao_order_order') . " WHERE oid = '$oid'";
					
					$agency_id = $GLOBALS['db']->getOne($sql);
					$order->oid = $oid;
					if (empty($agency_id))
					{
						$GLOBALS['db']->autoExecuteJson($GLOBALS['ecs']->table('taobao_order_order'), $order, 'INSERT', '', 'SILENT');
						if ($error_no > 0 && $error_no != 1062)
						{
							die($GLOBALS['db']->errorMsg());
						}
					}
					else
					{
						$GLOBALS['db']->autoExecuteJson($GLOBALS['ecs']->table('taobao_order_order'), $order, 'UPDATE', '`oid`='.$oid, 'SILENT');
						if ($error_no > 0 && $error_no != 1062)
						{
							die($GLOBALS['db']->errorMsg());
						}
					}
					
					$sql = "update ".$GLOBALS['ecs']->table('taobao_order_order')." set tid=$tid where oid=$oid";
					$GLOBALS['db']->query($sql);
				}
				
				if($trade->has_buyer_message || $trade->seller_flag != 0)
				{
					$req2 = new TradeFullinfoGetRequest();
					$req2->setFields("buyer_message,seller_memo,trade_memo,buyer_alipay_no");
					$req2->setTid($tid);
					$res = $c->execute($req2,$session);
					
					if(!empty($res->trade))
					{
						$tra = $res->trade;
						$sql = "update ".$GLOBALS['ecs']->table('taobao_order')." set buyer_message='".addslashes($tra->buyer_message)."',trade_memo='$tra->trade_memo',buyer_alipay_no='$tra->buyer_alipay_no' ,seller_memo='".addslashes($tra->seller_memo)."' where tid=$tid";
						$GLOBALS['db']->query($sql);
					}
				}
			}
		}
	}

	$GLOBALS['db']->query('UPDATE ' . $GLOBALS['ecs']->table('taobao_import') . ' SET last_import_time = "' . local_date('Y-m-d H:i:s'). '" WHERE id=1');
	
	make_json_result('');
}

function order_import_increment($lastTime,$session) {
	$page_size = 40;
	$fields = 'seller_nick, buyer_nick, title, type, created, tid, seller_rate, buyer_rate, status, payment, discount_fee, adjust_fee, post_fee, total_fee, pay_time, end_time, modified, consign_time, buyer_obtain_point_fee, point_fee, real_point_fee, received_payment, pic_path, num_iid, num, price, cod_fee, cod_status, shipping_type, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address, receiver_zip, receiver_mobile, receiver_phone,seller_flag,alipay_id,alipay_no,is_lgtype,is_force_wlb,is_brand_sale,buyer_area,has_buyer_message, credit_card_fee,orders';
	
	
	include_once ROOT_PATH.'includes/modules/taobao/top/request/TradesSoldGetRequest.php';
	include_once ROOT_PATH.'includes/modules/taobao/top/request/TradesSoldIncrementGetRequest.php';
	include_once ROOT_PATH.'includes/modules/taobao/top/request/TradeFullinfoGetRequest.php';
	$c = new TopClient;
	
	$req = new TradesSoldIncrementGetRequest();
	$req->setStartModified($lastTime);
	
	$maxTime = strtotime('+1 day',strtotime($lastTime));
	$nowTime = local_gettime();
	
	if ($maxTime <= $nowTime) {
		$hasNext = true;
		$updateTime = date('Y-m-d H:i:s',$maxTime);
	}else{
		$updateTime = date('Y-m-d H:i:s',$nowTime);
		$hasNext = false;
	}
	$req->setEndModified($updateTime);

	$page = 1;
	
	$req->setFields($fields);
	$req->setPageSize($page_size);
	$req->setPageNo($page);
	$res = $c->execute($req, $session);
	
	if(!empty($res->code))
	{
		if($res->code == "27"){
			$url = 'http://container.api.taobao.com/container?appkey='.$c->appkey.'&encode=utf-8';
			make_json_result('','1','淘宝帐户已过期，请重新登录。',array('url'=>$url,'code'=>$res->code));
		}else{
			if(isset($res->sub_msg)){
				$msg = $res->sub_msg;
			}else {
				$msg = $res->msg;
			}
			make_json_result('','1',$msg,array('code'=>$res->code));
		}
	}
	
	$total = $res->total_results;
	
	while($total > ($page-1) * $page_size)
	{
		if($page>1){
			$req->setPageNo($page);
			$res = $c->execute($req, $session);
		}
		
		$page++;
		
		
		if (!empty($res->trades->trade))
		{
			foreach ($res->trades->trade as $trade )
			{
				$tid =	sprintf('%.0f',$trade->tid);
				$sql = "SELECT tid FROM " . $GLOBALS['ecs']->table('taobao_order') . " WHERE tid = '$tid'";
				
				$agency_id = $GLOBALS['db']->getOne($sql);
				
				$trade->tid = $tid;
				if (empty($agency_id))
				{
					$GLOBALS['db']->autoExecuteJson($GLOBALS['ecs']->table('taobao_order'), $trade, 'INSERT', '', 'SILENT');
					if ($error_no > 0 && $error_no != 1062)
					{
						die($GLOBALS['db']->errorMsg());
					}				
				}
				else
				{
					$GLOBALS['db']->autoExecuteJson($GLOBALS['ecs']->table('taobao_order'), $trade, 'UPDATE', '`tid`='.$tid, 'SILENT');
					if ($error_no > 0 && $error_no != 1062)
					{
						die($GLOBALS['db']->errorMsg());
					}
				}
				
				foreach($trade->orders->order as $order)
				{
					$oid =	sprintf('%.0f',$order->oid);
					$sql = "SELECT tid FROM " . $GLOBALS['ecs']->table('taobao_order_order') . " WHERE oid = '$oid'";
					
					$agency_id = $GLOBALS['db']->getOne($sql);
					$order->oid = $oid;
					if (empty($agency_id))
					{
						$GLOBALS['db']->autoExecuteJson($GLOBALS['ecs']->table('taobao_order_order'), $order, 'INSERT', '', 'SILENT');
						if ($error_no > 0 && $error_no != 1062)
						{
							die($GLOBALS['db']->errorMsg());
						}
					}
					else
					{
						$GLOBALS['db']->autoExecuteJson($GLOBALS['ecs']->table('taobao_order_order'), $order, 'UPDATE', '`oid`='.$oid, 'SILENT');
						if ($error_no > 0 && $error_no != 1062)
						{
							die($GLOBALS['db']->errorMsg());
						}
					}
					
					$sql = "update ".$GLOBALS['ecs']->table('taobao_order_order')." set tid=$tid where oid=$oid";
					$GLOBALS['db']->query($sql);
				}
				
				if($trade->has_buyer_message || $trade->seller_flag != 0)
				{
					$req2 = new TradeFullinfoGetRequest();
					$req2->setFields("buyer_message,seller_memo,trade_memo,buyer_alipay_no");
					$req2->setTid($tid);
					$res = $c->execute($req2,$session);
					
					if(!empty($res->trade))
					{
						$tra = $res->trade;
						$sql = "update ".$GLOBALS['ecs']->table('taobao_order')." set buyer_message='".addslashes($tra->buyer_message)."',trade_memo='$tra->trade_memo',buyer_alipay_no='$tra->buyer_alipay_no' ,seller_memo='".addslashes($tra->seller_memo)."' where tid=$tid";
						$GLOBALS['db']->query($sql);
					}
				}
			}
		}
	}

	$GLOBALS['db']->query('UPDATE ' . $GLOBALS['ecs']->table('taobao_import') . ' SET last_import_time = "' . $updateTime. '" WHERE id=1');
	
	if ($hasNext) {
		make_json_result('','0','',array('hasNext'=>1));
	}else {
		make_json_result('');
	}
	
}

if ($_REQUEST['act'] == 'callback')
{
	$top_appkey = $_REQUEST['top_appkey']; 
	$top_parameters = $_REQUEST['top_parameters']; 
	$top_session = $_REQUEST['top_session']; 
	$top_sign = $_REQUEST['top_sign']; 

	$md5 = md5( $top_appkey . $top_parameters . $top_session . $appSecret, true ); 
	$sign = base64_encode( $md5 ); 

	if ( $sign != $top_sign ) { 
		//echo "signature invalid."; 
		//exit(); 
	} 
	
	$parameters = array(); 
	parse_str( base64_decode( $top_parameters ), $parameters ); 
	
	$sql = "update ".$GLOBALS['ecs']->table('taobao')."set `session`='".$_REQUEST['top_session']."' , `nick`='".$parameters['visitor_nick']."'";
	
	$GLOBALS['db']->query($sql,'CILENT');
	
	ecs_header("Location: index.php\n");
	exit;
}

if ($_REQUEST['act'] == 'list')
{
	/* 检查权限 */
	admin_priv('order_view');
	
	$status = $_REQUEST['status'];

	/* 模板赋值 */
	$smarty->assign('ur_here', $_LANG['taobao_order_list']);
	$smarty->assign('action_link', array('href' => 'taobao_order.php?act=order_import', 'text' => $_LANG['taobao_order_import']));

	include_once ROOT_PATH.'includes/modules/taobao/TopSdk.php';
	include_once ROOT_PATH.'includes/modules/taobao/top/TopClient.php';
	$c = new TopClient();

	$smarty->assign('appkey',$c->appkey);

	$smarty->assign('os_unconfirmed',   OS_UNCONFIRMED);
	$smarty->assign('cs_await_pay',     CS_AWAIT_PAY);
	$smarty->assign('cs_await_ship',    CS_AWAIT_SHIP);
	$smarty->assign('full_page',        1);
	$smarty->assign('status', $status);

	$order_list = taobao_order_list();
	$smarty->assign('order_list',   $order_list['orders']);
	$smarty->assign('filter',       $order_list['filter']);
	$smarty->assign('record_count', $order_list['record_count']);
	$smarty->assign('page_count',   $order_list['page_count']);
	$smarty->assign('sort_order_time', '<img src="images/sort_desc.gif">');

	$sql = 'SELECT last_import_time FROM '.$GLOBALS['ecs']->table('taobao_import').' WHERE id=1';
	$row = $GLOBALS['db']->getOne($sql);
	
	$lastTime = $row;
	
	if ($lastTime == null) {
		$lastTime = "尚未同步";
	}
	
	$smarty->assign('lastTime', $lastTime);
	
	/* 显示模板 */
	assign_query_info();
	$smarty->display('taobao_order_list.htm');
}

/*------------------------------------------------------ */
//-- 排序、分页、查询
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'query')
{
	/* 检查权限 */
	admin_priv('order_view');

	$order_list = taobao_order_list();

	$smarty->assign('order_list',   $order_list['orders']);
	$smarty->assign('filter',       $order_list['filter']);
	$smarty->assign('record_count', $order_list['record_count']);
	$smarty->assign('page_count',   $order_list['page_count']);
	$sort_flag  = sort_flag($order_list['filter']);
	$smarty->assign($sort_flag['tag'], $sort_flag['img']);
	make_json_result($smarty->fetch('taobao_order_list.htm'), '', array('filter' => $order_list['filter'], 'page_count' => $order_list['page_count']));
}

/**
 *  获取淘宝订单列表信息
 *
 * @access  public
 * @param
 *
 * @return void
 */
function taobao_order_list()
{
	$result = get_filter();
	if ($result === false)
	{
		$where = 'where 1=1 ';

		//     	订单状态
		$filter['status'] =  empty($_REQUEST['status']) ? 'DESC' : trim($_REQUEST['status']);

		switch($filter['status'])
		{
			case 'payed' :
				$where .= ' and o.status = "WAIT_SELLER_SEND_GOODS"';
				break;

			case 'unpay' :
				$where .=  ' and o.status = "WAIT_BUYER_PAY"';
				break;

			case 'delivery' :
				$where .= ' and o.status = "WAIT_BUYER_CONFIRM_GOODS"';
				break;

			case 'success' :
				$where .= ' and o.status = "TRADE_FINISHED"';
				break;
			case 'close' :
				$where .= ' and (o.status = "TRADE_CLOSED_BY_TAOBAO" or o.status = "TRADE_CLOSED")';
				break;
			case 'refund' :
				$where .= ' and o.status = "REFUND"';
				break;

			default:
				break;
		}
		
		/* 分页大小 */
		$filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);

		if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
		{
			$filter['page_size'] = intval($_REQUEST['page_size']);
		}
		elseif (isset($_COOKIE['ECSCP']['page_size']) && intval($_COOKIE['ECSCP']['page_size']) > 0)
		{
			$filter['page_size'] = intval($_COOKIE['ECSCP']['page_size']);
		}
		else
		{
			$filter['page_size'] = 15;
		}

		$sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('taobao_order') . " AS o ". $where;

		$filter['record_count']   = $GLOBALS['db']->getOne($sql);
		$filter['page_count']     = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1;

		/* 查询 */
		$sql = "SELECT o.tid, o.num, oo.num_iid, o.`status`, o.type, o.price, o.discount_fee, o.point_fee, o.total_fee, o.is_lgtype, o.is_brand_sale, o.is_force_wlb, o.created, o.pay_time, o.modified, o.end_time, o.alipay_id, o.alipay_no, o.seller_flag, o.buyer_nick, o.buyer_area, o.has_buyer_message, o.credit_card_fee, o.nut_feature, o.shipping_type, o.adjust_fee, o.buyer_obtain_point_fee, o.cod_fee, o.trade_from, o.cod_status, o.commission_fee, o.seller_nick, o.pic_path, o.payment, o.seller_rate, o.buyer_rate, o.real_point_fee, o.post_fee, o.receiver_name, o.receiver_status, o.receiver_state, o.receiver_city, o.receiver_district, o.receiver_address, o.receiver_zip, o.receiver_mobile, o.receiver_phone, o.consign_time, o.received_payment, o.item_meal_id, o.sku_id, o.outer_sku_id, o.sku_properties_name, o.refund_id, o.is_oversold, o.is_service_order, o.item_meal_name, o.refund_status, o.outer_iid, o.snapshot_url, o.`snapshot`, o.timeout_action_time, o.seller_type, o.cid, o.buyer_message, o.trade_memo, o.buyer_alipay_no,o.seller_memo, oo.title ".
			" FROM " . $GLOBALS['ecs']->table('taobao_order') ." AS o LEFT JOIN ".$GLOBALS['ecs']->table('taobao_order_order')." AS oo ON o.tid = oo.tid ".
			$where.
			" ORDER BY `created` desc".
			" LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ",$filter[page_size]";

		set_filter($filter, $sql);
	}
	else
	{
		$sql    = $result['sql'];
		$filter = $result['filter'];
	}
	
	$rows = new ArrayObject();
	$rows = $GLOBALS['db']->getAll($sql);

	/* 格式话数据 */
	for($i=0;$i<count($rows);$i++)
	{
		$key = 'status';
		$value = $rows[$i][$key];

		switch ($value) {
			case 'WAIT_BUYER_PAY':
				$rows[$i][$key]  = '未付款';
				break;
			case 'WAIT_SELLER_SEND_GOODS':
				$rows[$i][$key]  = '买家已付款';
				break;
			case 'WAIT_BUYER_CONFIRM_GOODS':
				$rows[$i][$key] = '已发货';
				break;
			case 'TRADE_FINISHED':
				$rows[$i][$key] = '交易成功';
				break;
			case 'TRADE_CLOSED':
				$rows[$i][$key] = '交易关闭，退款成功';
				break;
			case 'TRADE_CLOSED_BY_TAOBAO':
				$rows[$i][$key] = '交易关闭';
				break;
			default:
				;
				break;
		}

		
		if($rows[$i]['post_fee'] != '0.00')
		{
			$rows[$i]['post_fee'] = '含快递:'.$value.'元';
		}
		else
		{
			$rows[$i]['post_fee'] = '卖家包邮';
		}
		
		if ($rows[$i]['seller_memo'] == null) {
			$rows[$i]['seller_memo'] = '';
		}
	}
	$arr = array('orders' => $rows, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);

	return $arr;
}

/**
 * 获取站点根目录网址
 *
 * @access  private
 * @return  Bool
 */
function get_site_root_url()
{
	return 'http://' . $_SERVER['HTTP_HOST'] . str_replace('/' . ADMIN_PATH . '/order.php', '', PHP_SELF);
}
?>